import 'dart:math' show Point, min;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../game/game_controller.dart';
import '../game/game_board.dart';

class GameScreen extends StatefulWidget {
  final int gridSize;
  final int initialSpeed;

  const GameScreen({super.key, this.gridSize = 15, this.initialSpeed = 200});

  @override
  State<GameScreen> createState() => _GameScreenState();
}

class _GameScreenState extends State<GameScreen> {
  late GameController _gameController;
  final FocusNode _focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    _gameController = GameController(widget.gridSize, () => setState(() {}));
    _gameController.speed = widget.initialSpeed;
    _gameController.start();
  }

  @override
  void dispose() {
    _gameController.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
    if (event is KeyDownEvent) {
      if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
        _gameController.snake.changeDirection(Point(0, -1));
        return KeyEventResult.handled;
      } else if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
        _gameController.snake.changeDirection(Point(0, 1));
        return KeyEventResult.handled;
      } else if (event.logicalKey == LogicalKeyboardKey.arrowLeft) {
        _gameController.snake.changeDirection(Point(-1, 0));
        return KeyEventResult.handled;
      } else if (event.logicalKey == LogicalKeyboardKey.arrowRight) {
        _gameController.snake.changeDirection(Point(1, 0));
        return KeyEventResult.handled;
      } else if (event.logicalKey == LogicalKeyboardKey.space) {
        setState(() {
          if (_gameController.isPaused) {
            _gameController.resume();
          } else {
            _gameController.pause();
          }
        });
        return KeyEventResult.handled;
      }
    }
    return KeyEventResult.ignored;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('得分: ${_gameController.score}'),
        actions: [
          IconButton(
            icon: Icon(
              _gameController.isPaused ? Icons.play_arrow : Icons.pause,
            ),
            onPressed: () {
              setState(() {
                if (_gameController.isPaused) {
                  _gameController.resume();
                } else {
                  _gameController.pause();
                }
              });
            },
          ),
        ],
      ),
      body: Focus(
        focusNode: _focusNode,
        autofocus: true,
        onKeyEvent: _handleKeyEvent,
        child: GestureDetector(
          onVerticalDragUpdate: (details) {
            if (details.delta.dy > 0) {
              _gameController.snake.changeDirection(Point(0, 1)); // 下
            } else if (details.delta.dy < 0) {
              _gameController.snake.changeDirection(Point(0, -1)); // 上
            }
          },
          onHorizontalDragUpdate: (details) {
            if (details.delta.dx > 0) {
              _gameController.snake.changeDirection(Point(1, 0)); // 右
            } else if (details.delta.dx < 0) {
              _gameController.snake.changeDirection(Point(-1, 0)); // 左
            }
          },
          child: LayoutBuilder(
            builder: (context, constraints) {
              double size =
                  min(constraints.maxWidth, constraints.maxHeight) * 0.8;
              return Center(
                child: SizedBox(
                  width: size,
                  height: size,
                  child: GameBoard(
                    snake: _gameController.snake,
                    food: _gameController.food,
                    gridSize: widget.gridSize,
                    isGameOver: _gameController.isGameOver,
                  ),
                ),
              );
            },
          ),
        ),
      ),
      floatingActionButton: _gameController.isGameOver
          ? FloatingActionButton(
              onPressed: () {
                setState(() {
                  _gameController.reset();
                  _gameController.start();
                });
                _focusNode.requestFocus(); // 重新获取焦点
              },
              child: const Icon(Icons.refresh),
            )
          : null,
    );
  }
}
